package com.ruoyi.web.core.config;

import com.github.alenfive.rocketapi.config.RocketApiProperties;
import com.github.alenfive.rocketapi.entity.ApiInfo;
import com.github.alenfive.rocketapi.entity.ApiParams;
import com.github.alenfive.rocketapi.entity.vo.IgnoreWrapper;
import com.github.alenfive.rocketapi.extend.IApiPager;
import com.github.alenfive.rocketapi.service.ScriptParseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class RocketPagerConfig implements IApiPager {
    @Autowired
    private ScriptParseService parseService;

    @Autowired
    private RocketApiProperties rocketApiProperties;
    @Override
    public Object buildPager(Long totalRecords, List data, ApiInfo apiInfo, ApiParams apiParams) {

        Map<String,Object> pager = new HashMap<>();
        pager.put("code",200);
        pager.put("msg","查询成功");

        pager.put(rocketApiProperties.getPager().getTotalRecordsVarName(),totalRecords);
        pager.put(rocketApiProperties.getPager().getDataVarName(),data);

        final IgnoreWrapper pagerResponseEntity = IgnoreWrapper.builder()
                .data(pager)
                .build();
        return pagerResponseEntity;
    }

    @Override
    public String getPageSizeVarName() {
        return "pageSize";
    }

    @Override
    public String getPageNoVarName() {
        return "pageNum";
    }

    @Override
    public String getOffsetVarName() {
        return "index";
    }

    @Override
    public Integer getOffset(Integer pageSize, Integer pageNo) {
        int offset = (pageNo-1)* pageSize;
        return Math.max(offset, 0);
    }

    @Override
    public Integer getPageNo() {
        Object value = parseService.buildContentScopeParamItem(null,this.getPageNoVarName());
        if (StringUtils.isEmpty(value)){
            return rocketApiProperties.getPager().getDefaultPageNoValue();
        }
        return Integer.valueOf(value.toString());
    }

    @Override
    public Integer getPageSize() {
        Object value = parseService.buildContentScopeParamItem(null,this.getPageSizeVarName());
        if (StringUtils.isEmpty(value)){
            return rocketApiProperties.getPager().getDefaultPageSizeValue();
        }
        return Integer.valueOf(value.toString());
    }
}
